<script setup>
  import { useOrganizationTree } from '@/hooks/useOrganizationTree';
  import { NstdMessage } from 'nstd-components-pc-v3';
  const attrs = useAttrs();
  const emits = defineEmits(['confirm']);
  const props = defineProps({
    // 是否多选
    multiple: {
      type: Boolean,
      default: false
    }
  });
  const treeRef = ref();
  // 选中的节点
  const selection = computed(() => {
    return unref(treeRef).getCheckedNodes();
  });
  const { data } = useOrganizationTree();
  const defaultProps = {
    label: 'orgName',
    children: 'children'
  };
  function handleClear() {
    unref(treeRef)?.setCheckedNodes([]);
  }
  function handleConfirm() {
    if (selection.value.length === 0) {
      return NstdMessage.warning('请选择一个部门');
    }
    // 单选只能选择一条数据
    if (!props.multiple && NstdMessage.value.length !== 1) {
      return NstdMessage.warning('只能选择一个部门');
    }
    // 所有的条件都满足才抛出confirm事件
    emits('confirm', unref(NstdMessage));
  }
  function handleClose() {
    handleClear();
  }
  function handleCheckChange(node, check) {
    if (!props.multiple) {
      if (NstdMessage.value.length > 1) {
        nextTick(() => {
          unref(treeRef)?.setCheckedNodes(NstdMessage.value, false);
          unref(treeRef)?.setCheckedNodes([node], check);
        });
      }
    }
  }
  defineExpose({
    clear: handleClear
  });
</script>

<template>
  <NstdDialog title="选择部门" v-bind="attrs" @close="handleClose">
    <NstdScrollbar height="550">
      <NstdTree
        node-key="id"
        class="bg-blue-700"
        show-checkbox
        check-strictly
        :ref="(el) => (treeRef = el)"
        :default-expand-all="true"
        :data="data"
        :props="defaultProps"
        @check-change="handleCheckChange"
      />
    </NstdScrollbar>
    <div class="h-40px flex-center">
      <NstdButton type="primary" @click="handleConfirm">确认</NstdButton>
    </div>
  </NstdDialog>
</template>

<style scoped lang="scss"></style>
